import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';

const { createMessage } = useMessage();

enum Api {
  list = '/goods/goods/list',
  exportByFields = '/goods/goods/exportByFields',
}

/**
 * 列表接口
 * @param params
 */
export const list = (params) => defHttp.get({ url: Api.list, params });

//获取产品修改记录
export const getChangeLogList = (params) => defHttp.get({ url: Api.list, params });

/**
 * 自定义导出api
 * @param params
 * queryParam 是筛选查询参数
 */
export const getExportByFields = (queryParam, params) => {
  return defHttp.post({ url: Api.exportByFields, params: queryParam, data: params, responseType: 'blob' }, { isTransformResponse: false });
};
/**
 * 自定义导出并下载文件
 * @param name 文件名
 * @param queryParam 查询参数
 * @param params 导出字段参数
 */
export const handleExportByFields = async (name, queryParam, params) => {
  try {
    //update-begin---author:wangshuai---date:2024-01-25---for:【QQYUN-8118】导出超时时间设置长点---
    const data = await defHttp.post(
      { url: Api.exportByFields, params: queryParam, data: params, responseType: 'blob', timeout: 60000 },
      { isTransformResponse: false }
    );
    //update-end---author:wangshuai---date:2024-01-25---for:【QQYUN-8118】导出超时时间设置长点---
    if (!data) {
      createMessage.warning('文件下载失败');
      return;
    }
    //update-begin---author:wangshuai---date:2024-04-18---for: 导出excel失败提示，不进行导出---
    const reader = new FileReader();
    reader.readAsText(data, 'utf-8');
    reader.onload = async () => {
      if (reader.result) {
        if (reader.result.toString().indexOf('success') != -1) {
          // update-begin---author:liaozhiyang---date:2025-02-11---for:【issues/7738】文件中带"success"导出报错 ---
          try {
            const { success, message } = JSON.parse(reader.result.toString());
            if (!success) {
              createMessage.warning('导出失败，失败原因：' + message);
            } else {
              downloadExportFile(name, data);
            }
            return;
          } catch (error) {
            downloadExportFile(name, data);
          }
          // update-end---author:liaozhiyang---date:2025-02-11---for:【issues/7738】文件中带"success"导出报错 ---
        }
      }
      downloadExportFile(name, data);
      //update-end---author:wangshuai---date:2024-04-18---for: 导出excel失败提示，不进行导出---
    };
  } catch (error) {
    createMessage.warning('导出失败:' + error.message);
  }
};
/**
 * 下载导出的文件
 * @param name 文件名
 * @param data 文件数据
 */
function downloadExportFile(name, data) {
  if (!name || typeof name !== 'string') {
    name = '导出文件';
  }

  const blobOptions = { type: 'application/vnd.ms-excel' };
  const fileSuffix = '.xls';

  if (typeof window.navigator.msSaveBlob !== 'undefined') {
    window.navigator.msSaveBlob(new Blob([data], blobOptions), name + fileSuffix);
  } else {
    const url = window.URL.createObjectURL(new Blob([data], blobOptions));
    const link = document.createElement('a');
    link.style.display = 'none';
    link.href = url;
    link.setAttribute('download', name + fileSuffix);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link); //下载完成移除元素
    window.URL.revokeObjectURL(url); //释放掉blob对象
  }
}
